package io.github.consoles.dsa;

import java.util.Iterator;

/**
 * Created by yiihua-013 on 17/9/7.
 * <p>
 * 用一个双向队列实现两个栈，保证每个栈操作只需要常数次的双向队列操作。
 */
public class LinkedDeStack<Item> implements Iterable<Item> {

    private DoubleNode<Item> first, last;
    private int leftCount, rightCount;

    /**
     * 向左栈添加元素
     */
    public void pushLeft(Item item) {
        DoubleNode<Item> oldFirst = first;
        DoubleNode<Item> node = new DoubleNode<>(item);
        node.next = oldFirst;
        node.prev = null;
        first = node;
        if (oldFirst == null) last = node;
        else oldFirst.prev = node;
        leftCount++;
    }

    public boolean isLeftEmpty() {
        return leftCount == 0;
    }

    public boolean isRightEmpty() {
        return rightCount == 0;
    }

    public int getLeftSize() {
        return leftCount;
    }

    public int getRightSize() {
        return rightCount;
    }

    /**
     * 向右栈添加元素
     */
    public void pushRight(Item item) {
        DoubleNode<Item> oldLast = last;
        DoubleNode<Item> node = new DoubleNode<>(item);
        node.prev = oldLast;
        node.next = null;
        last = node;
        if (oldLast == null) first = node;
        else oldLast.next = node;
        rightCount++;
    }

    public Item popLeft() {
        if (isLeftEmpty()) throw new RuntimeException("左栈空,不能出");
        Item item = first.item;
        first = first.next;
        leftCount--;
        if (first == null) last = null;
        else first.prev = null;
        return item;
    }

    public Item popRight() {
        if (isRightEmpty()) throw new RuntimeException("右栈空,不能出");
        Item item = last.item;
        last = last.prev;
        rightCount--;
        if (last == null) first = null;
        else last.next = null;
        return item;
    }

    @Override
    public Iterator<Item> iterator() {
        return new LinkedDeStackIterator();
    }

    private class LinkedDeStackIterator implements Iterator<Item> {

        DoubleNode<Item> current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}
